package com.medical_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.medical_backend.entity.Insured;
import com.medical_backend.entity.Result;
import com.medical_backend.service.InsuredService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/insured")
public class InsuredController {
    @Autowired
    InsuredService insuredService;
    //获取区域信息列表
    @GetMapping("/list")
    public Result list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {
        QueryWrapper<Insured> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            queryWrapper.lambda().like(Insured::getInsuredName, keyword).or().like(Insured::getCardId, keyword);
        }
        Page<Insured> pageInfo = insuredService.page(new Page<>(page, size),queryWrapper);
        return new Result("查询成功",pageInfo,200);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Insured insured) {
        // 避免前端误传 id，手动置空
        insured.setId(null);

        boolean save = insuredService.save(insured);
        if (save) {
            return new Result("新增成功", insured, 200);
        } else {
            return new Result("新增失败", null, 500);
        }
    }

    @PostMapping("/edit")
    public Result edit(@RequestBody Insured insured) {
        // 确保传入了 id，用于更新
        if (insured.getId() == null) {
            return new Result("参合ID不能为空", null, 400);
        }

        boolean updated = insuredService.updateById(insured);
        if (updated) {
            return new Result("修改成功", insured, 200);
        } else {
            return new Result("修改失败", null, 500);
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        boolean isDeleted = insuredService.removeById(id);
        if (isDeleted) {
            return new Result("删除成功", null, 200);
        } else {
            return new Result("删除失败: 参合信息不存在", null, 404);
        }
    }

    // 用于前端远程模糊搜索参合人（身份证号或姓名）
    @GetMapping("/search")
    public Result search(@RequestParam String keyword) {
        QueryWrapper<Insured> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            queryWrapper.lambda()
                    .like(Insured::getInsuredName, keyword)
                    .or()
                    .like(Insured::getCardId, keyword);
        }
        // 限制最多返回前 10 个匹配结果
        Page<Insured> page = new Page<>(1, 10);
        Page<Insured> result = insuredService.page(page, queryWrapper);
        return new Result("查询成功", result.getRecords(), 200);
    }
}
